#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
智能报告模板定义

提供标准化的报告模板，确保生成的报告具有一致的结构和格式。
"""

from datetime import datetime
from typing import Dict, Any, List, Optional

class ReportTemplates:
    """报告模板类"""
    
    @staticmethod
    def get_comprehensive_template() -> Dict[str, Any]:
        """获取综合分析报告模板"""
        return {
            "template_name": "综合分析报告",
            "template_id": "comprehensive_analysis",
            "sections": [
                {
                    "id": "executive_summary",
                    "title": "执行摘要",
                    "icon": "fas fa-chart-line",
                    "order": 1,
                    "required": True,
                    "description": "报告的核心发现和关键洞察概述"
                },
                {
                    "id": "data_overview",
                    "title": "数据概览",
                    "icon": "fas fa-database",
                    "order": 2,
                    "required": True,
                    "description": "数据集的基本信息和质量评估"
                },
                {
                    "id": "descriptive_statistics",
                    "title": "描述性统计",
                    "icon": "fas fa-calculator",
                    "order": 3,
                    "required": True,
                    "description": "基本统计指标和分布特征"
                },
                {
                    "id": "correlation_analysis",
                    "title": "相关性分析",
                    "icon": "fas fa-project-diagram",
                    "order": 4,
                    "required": True,
                    "description": "变量间的关联关系分析"
                },
                {
                    "id": "cluster_analysis",
                    "title": "聚类分析",
                    "icon": "fas fa-sitemap",
                    "order": 5,
                    "required": False,
                    "description": "用户群体细分和特征识别"
                },
                {
                    "id": "ai_insights",
                    "title": "AI智能洞察",
                    "icon": "fas fa-brain",
                    "order": 6,
                    "required": False,
                    "description": "基于AI分析的深度洞察和模式发现"
                },
                {
                    "id": "recommendations",
                    "title": "建议与行动计划",
                    "icon": "fas fa-lightbulb",
                    "order": 7,
                    "required": True,
                    "description": "基于分析结果的具体建议和实施方案"
                },
                {
                    "id": "methodology",
                    "title": "分析方法论",
                    "icon": "fas fa-cogs",
                    "order": 8,
                    "required": True,
                    "description": "使用的分析方法和技术说明"
                }
            ],
            "metadata": {
                "created_at": datetime.now().isoformat(),
                "version": "1.0",
                "author": "SurveyAnalyzer AI",
                "description": "全面的问卷数据分析报告模板，包含统计分析、聚类分析和AI洞察"
            }
        }
    
    @staticmethod
    def get_executive_summary_template() -> Dict[str, Any]:
        """获取执行摘要报告模板"""
        return {
            "template_name": "执行摘要报告",
            "template_id": "executive_summary",
            "sections": [
                {
                    "id": "key_findings",
                    "title": "关键发现",
                    "icon": "fas fa-star",
                    "order": 1,
                    "required": True,
                    "description": "最重要的分析结果和发现"
                },
                {
                    "id": "data_highlights",
                    "title": "数据亮点",
                    "icon": "fas fa-chart-bar",
                    "order": 2,
                    "required": True,
                    "description": "数据中的突出特征和趋势"
                },
                {
                    "id": "business_impact",
                    "title": "业务影响",
                    "icon": "fas fa-business-time",
                    "order": 3,
                    "required": True,
                    "description": "分析结果对业务的潜在影响"
                },
                {
                    "id": "priority_actions",
                    "title": "优先行动",
                    "icon": "fas fa-tasks",
                    "order": 4,
                    "required": True,
                    "description": "基于分析结果的优先级行动建议"
                }
            ],
            "metadata": {
                "created_at": datetime.now().isoformat(),
                "version": "1.0",
                "author": "SurveyAnalyzer AI",
                "description": "面向管理层的简洁执行摘要报告模板"
            }
        }
    
    @staticmethod
    def get_technical_analysis_template() -> Dict[str, Any]:
        """获取技术分析报告模板"""
        return {
            "template_name": "技术分析报告",
            "template_id": "technical_analysis",
            "sections": [
                {
                    "id": "data_quality_assessment",
                    "title": "数据质量评估",
                    "icon": "fas fa-check-circle",
                    "order": 1,
                    "required": True,
                    "description": "数据完整性、准确性和一致性评估"
                },
                {
                    "id": "statistical_tests",
                    "title": "统计检验",
                    "icon": "fas fa-flask",
                    "order": 2,
                    "required": True,
                    "description": "假设检验和统计显著性分析"
                },
                {
                    "id": "model_performance",
                    "title": "模型性能",
                    "icon": "fas fa-tachometer-alt",
                    "order": 3,
                    "required": True,
                    "description": "聚类模型和分析算法的性能评估"
                },
                {
                    "id": "technical_details",
                    "title": "技术细节",
                    "icon": "fas fa-code",
                    "order": 4,
                    "required": True,
                    "description": "分析过程的技术实现和参数设置"
                },
                {
                    "id": "limitations",
                    "title": "局限性分析",
                    "icon": "fas fa-exclamation-triangle",
                    "order": 5,
                    "required": True,
                    "description": "分析方法和结果的局限性说明"
                }
            ],
            "metadata": {
                "created_at": datetime.now().isoformat(),
                "version": "1.0",
                "author": "SurveyAnalyzer AI",
                "description": "面向技术人员的详细技术分析报告模板"
            }
        }
    
    @staticmethod
    def get_presentation_template() -> Dict[str, Any]:
        """获取演示报告模板"""
        return {
            "template_name": "演示报告",
            "template_id": "presentation",
            "sections": [
                {
                    "id": "overview_slide",
                    "title": "概览",
                    "icon": "fas fa-eye",
                    "order": 1,
                    "required": True,
                    "description": "分析目标和数据概况"
                },
                {
                    "id": "key_metrics",
                    "title": "关键指标",
                    "icon": "fas fa-chart-pie",
                    "order": 2,
                    "required": True,
                    "description": "最重要的统计指标和KPI"
                },
                {
                    "id": "visual_insights",
                    "title": "可视化洞察",
                    "icon": "fas fa-chart-area",
                    "order": 3,
                    "required": True,
                    "description": "图表和可视化展示的关键发现"
                },
                {
                    "id": "user_segments",
                    "title": "用户细分",
                    "icon": "fas fa-users",
                    "order": 4,
                    "required": False,
                    "description": "用户群体特征和行为模式"
                },
                {
                    "id": "next_steps",
                    "title": "下一步行动",
                    "icon": "fas fa-arrow-right",
                    "order": 5,
                    "required": True,
                    "description": "基于分析结果的后续行动计划"
                }
            ],
            "metadata": {
                "created_at": datetime.now().isoformat(),
                "version": "1.0",
                "author": "SurveyAnalyzer AI",
                "description": "适合演示和汇报的简洁报告模板"
            }
        }
    
    @staticmethod
    def get_all_templates() -> Dict[str, Dict[str, Any]]:
        """获取所有可用的报告模板"""
        return {
            "comprehensive": ReportTemplates.get_comprehensive_template(),
            "executive_summary": ReportTemplates.get_executive_summary_template(),
            "technical": ReportTemplates.get_technical_analysis_template(),
            "presentation": ReportTemplates.get_presentation_template()
        }
    
    @staticmethod
    def get_template_by_id(template_id: str) -> Optional[Dict[str, Any]]:
        """根据ID获取特定模板"""
        templates = ReportTemplates.get_all_templates()
        return templates.get(template_id)
    
    @staticmethod
    def get_default_template() -> Dict[str, Any]:
        """获取默认模板（综合分析报告）"""
        return ReportTemplates.get_comprehensive_template()
    
    @staticmethod
    def validate_template(template: Dict[str, Any]) -> bool:
        """验证模板格式是否正确"""
        required_fields = ["template_name", "template_id", "sections", "metadata"]
        
        # 检查必需字段
        for field in required_fields:
            if field not in template:
                return False
        
        # 检查sections格式
        if not isinstance(template["sections"], list):
            return False
        
        for section in template["sections"]:
            section_required_fields = ["id", "title", "order", "required"]
            for field in section_required_fields:
                if field not in section:
                    return False
        
        return True
    
    @staticmethod
    def create_custom_template(name: str, sections: List[Dict[str, Any]], 
                             description: str = "") -> Dict[str, Any]:
        """创建自定义模板"""
        template_id = name.lower().replace(" ", "_").replace("-", "_")
        
        # 确保sections有正确的order
        for i, section in enumerate(sections):
            if "order" not in section:
                section["order"] = i + 1
            if "required" not in section:
                section["required"] = True
            if "icon" not in section:
                section["icon"] = "fas fa-file-alt"
        
        return {
            "template_name": name,
            "template_id": template_id,
            "sections": sections,
            "metadata": {
                "created_at": datetime.now().isoformat(),
                "version": "1.0",
                "author": "Custom",
                "description": description or f"自定义报告模板：{name}"
            }
        }

# 预定义的内容模板
CONTENT_TEMPLATES = {
    "executive_summary": {
        "template": """
## 执行摘要

### 关键发现
{key_findings}

### 数据概况
- 样本规模：{sample_size}
- 数据质量：{data_quality}
- 分析时间：{analysis_date}

### 主要洞察
{main_insights}

### 建议行动
{recommendations}
""",
        "variables": ["key_findings", "sample_size", "data_quality", "analysis_date", "main_insights", "recommendations"]
    },
    
    "data_overview": {
        "template": """
## 数据概览

### 基本信息
- **数据集大小**：{rows} 行 × {columns} 列
- **数据类型**：{data_types}
- **时间范围**：{time_range}

### 数据质量评估
- **完整性**：{completeness}%
- **缺失值**：{missing_values}
- **重复值**：{duplicates}
- **异常值**：{outliers}

### 变量分布
{variable_distribution}
""",
        "variables": ["rows", "columns", "data_types", "time_range", "completeness", "missing_values", "duplicates", "outliers", "variable_distribution"]
    },
    
    "ai_insights": {
        "template": """
## AI智能洞察

### 模式发现
{pattern_discovery}

### 趋势分析
{trend_analysis}

### 异常检测
{anomaly_detection}

### 预测性洞察
{predictive_insights}

### 业务建议
{business_recommendations}
""",
        "variables": ["pattern_discovery", "trend_analysis", "anomaly_detection", "predictive_insights", "business_recommendations"]
    }
}

# 样式模板
STYLE_TEMPLATES = {
    "professional": {
        "colors": {
            "primary": "#2c3e50",
            "secondary": "#3498db",
            "accent": "#e74c3c",
            "success": "#27ae60",
            "warning": "#f39c12",
            "info": "#17a2b8"
        },
        "fonts": {
            "heading": "'Segoe UI', Tahoma, Geneva, Verdana, sans-serif",
            "body": "'Segoe UI', Tahoma, Geneva, Verdana, sans-serif",
            "code": "'Courier New', Courier, monospace"
        }
    },
    
    "modern": {
        "colors": {
            "primary": "#667eea",
            "secondary": "#764ba2",
            "accent": "#f093fb",
            "success": "#4facfe",
            "warning": "#ffecd2",
            "info": "#a8edea"
        },
        "fonts": {
            "heading": "'Inter', -apple-system, BlinkMacSystemFont, sans-serif",
            "body": "'Inter', -apple-system, BlinkMacSystemFont, sans-serif",
            "code": "'Fira Code', 'Courier New', monospace"
        }
    }
}